package com.example.electricbicycle.controller;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.example.electricbicycle.po.User;
import com.example.electricbicycle.service.UserService;
import com.example.electricbicycle.service.UserServiceImpl;

@WebServlet("/DeleteUserServlet")
public class DeleteUserServlet extends HttpServlet {
    private final UserService userService = new UserServiceImpl();

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        request.setCharacterEncoding("UTF-8");
        HttpSession session = request.getSession();
        // 清除旧消息，避免消息重复
        session.removeAttribute("successMsg");
        session.removeAttribute("errorMsg");

        try {
            User currentUser = (User) session.getAttribute("currentUser");

            // 调试信息
            System.out.println("[DEBUG] 当前用户: "
                    + (currentUser != null ? currentUser.getName() : "null"));

            // 权限校验 - 确保只有管理员可以删除用户
            if (currentUser == null || currentUser.getRole() != 4) {
                session.setAttribute("errorMsg", "权限不足，只有管理员可以删除用户");
                response.sendRedirect(request.getContextPath() + "/UserListServlet");
                return;
            }

            // 参数校验
            String uidParam = request.getParameter("id");
            if (uidParam == null || uidParam.trim().isEmpty()) {
                session.setAttribute("errorMsg", "无效的用户ID");
                response.sendRedirect(request.getContextPath() + "/UserListServlet");
                return;
            }

            int uid = Integer.parseInt(uidParam);

            // 防止删除自己
            if (currentUser.getId() == uid) {
                session.setAttribute("errorMsg", "不能删除自己的账户");
                response.sendRedirect(request.getContextPath() + "/UserListServlet");
                return;
            }

            // 检查用户是否存在
            User userToDelete = userService.getUserById(uid);
            if (userToDelete == null) {
                session.setAttribute("errorMsg", "用户不存在");
                response.sendRedirect(request.getContextPath() + "/UserListServlet");
                return;
            }

            // 执行删除
            boolean isDeleted = userService.deleteUser(uid);

            // 结果处理 - 只设置一种消息
            if (isDeleted) {
                session.setAttribute("successMsg", "用户 '" + userToDelete.getName() + "' 删除成功");
            } else {
                // 仓库管理员可能有关联数据，无法删除
                if (userToDelete.getRole() == 1) {
                    session.setAttribute("errorMsg", "无法删除仓库管理员 '" + userToDelete.getName() + "'，该用户有关联数据");
                } else {
                    session.setAttribute("errorMsg", "用户 '" + userToDelete.getName() + "' 删除失败");
                }
            }

        } catch (NumberFormatException e) {
            session.setAttribute("errorMsg", "无效的用户ID格式");
        } catch (Exception e) {
            session.setAttribute("errorMsg", "系统错误: " + e.getMessage());
            e.printStackTrace();
        }

        // 最终重定向到用户列表
        response.sendRedirect(request.getContextPath() + "/UserListServlet");
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}